package org.applet.game.app.rpg.resource;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.applet.game.framework.util.ImageLoader;

public class SingleImageStore extends ImageStore {

	BufferedImage image;
	int width;
	int height;
	int imageSX;
	int imageSY;
	File resource;
	
	public SingleImageStore(File resource)
	{
		this.resource = resource;
		load();
	}
	
	@Override
	public BufferedImage getImage() {
		return image;
	}

	@Override
	public void load() {
		image = ImageLoader.loadImage(resource);
		Properties prop = new Properties();
		InputStream inStream;
		try {
			inStream = new FileInputStream(resource.getPath().replaceAll("\\.png", ".txt"));
			prop.load(inStream);
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		xFrameCount = Integer.valueOf(prop.getProperty("xFrame"));
		width = Integer.valueOf(prop.getProperty("width"));
		height = Integer.valueOf(prop.getProperty("height"));
	}

	@Override
	public void saveTo(File file) {
		// TODO Auto-generated method stub
	}

	@Override
	public void seftRender(Graphics painter, int x, int y, ImageObserver observer) {
		painter.drawImage(image, x, y, x+width, y+height, imageSX, imageSY, imageSX+width, imageSY+height, observer);
	}

	@Override
	public boolean shiftView(int x, int y) {
		imageSX = x*width;
		imageSY = y*height;
		return true;
	}

	@Override
	public boolean moveViewX(int x) {
		imageSX = x*width;
		return super.moveViewX(x);
	}

	@Override
	public boolean moveViewY(int y) {
		imageSY = y*height;
		return super.moveViewY(y);
	}

	public int getImageSX() {
		return imageSX;
	}

	public void setImageSX(int imageSX) {
		this.imageSX = imageSX;
	}

	public int getImageSY() {
		return imageSY;
	}

	public void setImageSY(int imageSY) {
		this.imageSY = imageSY;
	}

	@Override
	public boolean shiftNextX() {
		if(imageSX >= (xFrameCount-1)*width)
		{
			imageSX = 0;
			return false;
		}
		else
		{
			imageSX += width;
			return true;
		}
	}

	@Override
	public boolean shiftNextY() {
		if(imageSY >= (yFrameCount-1)*height)
		{
			imageSY = 0;
			return false;
		}
		else
		{
			imageSY += height;
			return true;
		}
	}

}
